<template>
  <div class="db_dialog">
    <el-form
      ref="form"
      :rules="rules"
      :model="form"
      label-position="left"
      label-width="110px"
    >
      <div class="step_box">
        <div :class="['step_item', step >= 1 && 'steped']">表定义</div>
        <div class="line"></div>
        <div :class="['step_item', step == 2 && 'steped']">字段定义</div>
      </div>
      <div class="edit_list" v-if="step == 1">
        <el-form-item label="数据库分类：" prop="databaseType">
          <el-select
            filterable
            class="bin_select"
            v-model="form.databaseType"
            @change="form.dataTypeId = ''"
            placeholder="请选择数据表分类"
          >
            <el-option
              v-for="(item, index) in kuOptions"
              :key="index"
              :label="item.databaseTypeName"
              :value="item.databaseType"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据表分类：" prop="dataTypeId">
          <el-select
            filterable
            class="bin_select"
            allow-create
            clearable
            :filterable="true"
            v-model="form.dataTypeId"
            placeholder="请选择数据表分类"
          >
            <el-option
              v-for="(item, index) in biaoOptionsDict[form.databaseType]"
              :key="index"
              :label="item.dataTypeName"
              :value="item.dataTypeId"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 用户不想输入该字段 -->
        <!-- <el-form-item label="数据表标识：" prop="dataTableCode">
          <el-tooltip content="数据表标识是程序中使用" placement="top-start">
            <el-input
              class="bin_input"
              v-model="form.dataTableCode"
              placeholder="数据表标识为英文及数字"
            >
            </el-input>
          </el-tooltip>
        </el-form-item> -->
        <el-form-item label="数据表标题：" prop="dataTableName">
          <el-tooltip
            content="数据表标题字段方面用户查看"
            placement="top-start"
          >
            <el-input
              class="bin_input"
              v-model="form.dataTableName"
              placeholder="数据表标题"
            >
            </el-input>
          </el-tooltip>
        </el-form-item>
      </div>
      <div class="columnBox" v-if="step == 2">
        <div
          class="columnIte"
          v-for="(item, index) in form.dataColumnVoList"
          :key="index"
        >
          <el-row v-if="index == 0">
            <el-col :span="6" class="flexrowbottom">
              <el-form-item label="预选元数据类型">
                <el-select
                  filterable
                  class="bin_select"
                  v-model="value1"
                  placeholder="请选择"
                  @change="
                    (checked) => {
                      changeSelect(checked, item, index);
                    }
                  "
                >
                  <el-option
                    v-for="(item1, index1) in columnOptions1"
                    :key="index1"
                    :label="item1.modelName"
                    :value="item1.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="flexrowbottom" style="width: 100%" v-if="!item.isDel">
            <el-col :span="6" class="flexrowbottom" style="margin-right: 10px">
              <el-form-item label="属性选择：">
                <el-select
                  filterable
                  class="bin_select"
                  v-model="item.fieldAttribute"
                  placeholder="请选择"
                  @change="changeType(item, index)"
                >
                  <el-option
                    v-for="(item1, index1) in yuanOptions"
                    :key="index1"
                    :label="item1"
                    :value="item1"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" class="flexrowbottom">
              <el-form-item label="字段名称选择：" required>
                <el-select
                  filterable
                  class="bin_select"
                  v-model="item.fieldDescription"
                  placeholder="请选择"
                  @change="changeType2(item, index)"
                >
                  <el-option
                    v-for="(item1, index1) in item.columnOptions3"
                    :key="index1"
                    :label="item1.fieldDescription"
                    :value="index1"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="2" style="margin-left: 10px">
              <el-form-item label="数据类型">
                <div>{{ item.columnType }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-form-item label="长度">
                <div>{{ item.fieldLength }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="3" class="flexrowbottom">
              <el-form-item label="必填">
                <el-checkbox-group v-model="item.value6" class="bin_checkout">
                  <el-checkbox label="1"> </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              <el-form-item label="显示">
                <el-checkbox-group v-model="item.value7" class="bin_checkout">
                  <el-checkbox label="1"> </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
            <el-col :span="5" class="flexrowbottom">
              <el-form-item>
                <el-button
                  class="bin_button"
                  icon="el-icon-top"
                  size="small"
                  @click="up(index)"
                >
                </el-button>
              </el-form-item>
              <el-form-item>
                <el-button
                  class="bin_button"
                  icon="el-icon-bottom"
                  size="small"
                  @click="dowm(index)"
                >
                </el-button>
              </el-form-item>
              <el-form-item>
                <el-button
                  class="bin_button"
                  icon="el-icon-delete"
                  size="small"
                  @click="deleteBtn(index, item)"
                >
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="addbtn">
          <el-button
            class="bin_button"
            icon="el-icon-plus"
            size="small"
            @click="addBtn22"
          >
          </el-button>
        </div>
      </div>
      <div class="edit_btns">
        <el-button class="bin_button" size="small" @click="cancelBtn">
          取消
        </el-button>
        <el-button
          class="bin_button"
          size="small"
          v-if="step == 1"
          @click="nextStep"
        >
          下一步
        </el-button>
        <el-button
          class="bin_button"
          size="small"
          v-if="step == 2"
          @click="step = 1"
        >
          上一步
        </el-button>
        <el-button
          class="bin_button"
          size="small"
          v-if="step == 2"
          @click="goLinkFn"
        >
          确认
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "menuItem",
  props: {
    tableAndHeader: {
      type: Object,
      default: () => {
        return {};
      },
    },
    pageshow: {
      type: Boolean,
      default: false,
    },
  },
  watch: {
    pageshow: {
      deep: true,
      immediate: true,
      handler: function (val) {
        if (!val) {
          this.step = 1;
          this.clearForm();
        }
      },
    },
    tableAndHeader: {
      // 深度观察监听
      deep: true,
      immediate: true,
      handler: function (val) {
        let data = JSON.parse(JSON.stringify(val));
        console.log("表格====", data, val);
        this.form = {
          databaseType: data.table.databaseType,
          dataTypeId: data.table.dataTypeId,
          // dataTableCode: data.table.dataTableCode,
          dataTableName: data.table.dataTableName,
          tableId: data.table.dataTableId,
          dataColumnVoList: data.header.map((e) => {
            console.log("e===", e);
            // e.fieldAttribute = e.columnName;
            // e.columnName = e.columnName;
            e.id = e.id;
            e.fieldDescription = e.columnCode;
            e.columnCode = e.columnCode;
            e.isExistent = true;
            // e.metadataDictyColId = e.metadataDictyColId;
            e.value6 = new Array(e.columnRequired);
            e.value7 = new Array(e.columnDisplay);
            return e;
          }),
        };
      },
    },
  },
  data() {
    return {
      step: 1,
      kuOptions: [],
      biaoOptionsDict: {},
      value1: "",
      columnOptions1: [],
      form: {},
      typeObj: {},
      typeOptions: [
        {
          label: "字符串",
          value: "STRING",
        },
        {
          label: "整数",
          value: "INT",
        },
        {
          label: "长整数",
          value: "LONG",
        },
        {
          label: "浮点数",
          value: "FLOAT",
        },
        {
          label: "双精度浮点数",
          value: "DOUBLE",
        },
        {
          label: "布尔值",
          value: "BOOLEAN",
        },
        {
          label: "日期",
          value: "DATE",
        },
        {
          label: "时间戳",
          value: "TIMESTAMP",
        },
        {
          label: "十进制",
          value: "DECIMAL",
        },
        {
          label: "二进制",
          value: "BINARY",
        },
        {
          label: "时间",
          value: "TIME",
        },
        {
          label: "大对象",
          value: "BLOB",
        },
        {
          label: "日期时间",
          value: "DATETIME",
        },
      ],
      yuanOptions: [],
      rules: {
        databaseType: [
          { required: true, message: "请选择数据库分类", trigger: "change" },
        ],
        dataTypeId: [
          { required: true, message: "请选择数据表分类", trigger: "change" },
        ],
        // dataTableCode: [
        //   { required: true, message: "请输入数据表标识", trigger: "change" },
        // ],
        dataTableName: [
          { required: true, message: "请输入数据表标题", trigger: "change" },
        ],
      },
    };
  },
  created() {
    console.log("chuangj");

    this.getDataType();
    this.getType();
    // this.getYuanDict();
    this.getcolumnOptions1();
  },
  mounted() {
    console.log("mounte");
  },
  before() {
    console.log("消除");
    this.clearForm();
  },
  methods: {
    getcolumnOptions1() {
      this.$api.moxingmenu().then((res) => {
        const { code, result } = res;
        if (code == 200) {
          this.columnOptions1 = result;
        }
      });
      this.$api.queryFieldAttributeGroup().then((res) => {
        const { code, result } = res;
        if (code == 200) {
          this.yuanOptions = result;
        }
      });
    },
    changeSelect(checkId, item, index) {
      console.log(item);
      let obj = {
        modelId: this.value1,
      };
      this.$api.queryElements(obj).then((res) => {
        const { code, result } = res;
        if (code == 200) {
          this.form.dataColumnVoList = result.map((res) => {
            return {
              fieldAttribute: res.fieldAttribute,
              fieldDescription: res.fieldDescription,
              fieldType: res.fieldType,
              fieldLength: res.fieldLength,
              value6: false,
              value7: true,
              columnOptions3: [],
              ...res,
            };
          });
        }
      });
      // item.id = checkId;
      // this.$set(this.form.dataColumnVoList, index, item);
    },

    changeType2(item, index) {
      let num = Number(item.fieldDescription);
      console.log(item);
      let selectItem = item.columnOptions3[num];
      delete selectItem.id;
      console.log(selectItem);

      this.$set(this.form.dataColumnVoList, index, {
        ...item,
        ...selectItem,
        columnType: item.columnOptions3[num].fieldType,
        metadataDictyId: item.columnOptions3[num].id,
      });
    },
    changeType(item, index) {
      let obj = {
        fieldAttribute: item.fieldAttribute,
      };
      this.$api.queryFieldByFieldAttribute(obj).then((res) => {
        const { code, result } = res;
        if (code == 200) {
          console.log(item);

          this.$set(this.form.dataColumnVoList, index, {
            ...item,
            fieldAttribute: item.fieldAttribute,
            columnOptions3: result,
            value6: false,
            value7: false,
          });
        }
      });
      // this.$api
      //   .findByTableId({
      //     metadataDictyTableId: item.metadataDictyTableId,
      //     pageNum: 1,
      //     pageSize: 4096,
      //   })
      //   .then((res) => {
      //     if (res.code == 200) {
      //       item.metadataDictyColId = "";
      //       item.columnOptions = res.result.content;
      //       this.$set(this.form.dataColumnVoList, index, item);
      //     }
      //   });
    },
    getYuanDict() {
      this.$api.getAllTree().then((res) => {
        let arr1 = JSON.parse(JSON.stringify(res.result["结构化"]));
        let arr2 = JSON.parse(JSON.stringify(res.result["非结构化"]));
        this.yuanOptions = arr1.concat(arr2);
      });
    },
    nextStep() {
      this.step = 2;
    },
    getType() {
      this.$api.getMetadataType().then((res) => {
        if (res.code == 200) {
          this.typeOptions = res.result;
          let obj = {};
          res.result.map((e, i, v) => {
            obj[e.value] = e.label;
          });
          this.typeObj = obj;
        }
      });
    },
    cancelBtn() {
      this.$emit("cancel");
    },
    getDataType() {
      this.$api.ysjtqGetFileTypeApi(3).then((res) => {
        if (res.code == 200) {
          this.kuOptions = res.result;
          this.kuOptions.forEach((item) => {
            this.biaoOptionsDict[item.databaseType] = item.dataTypeVoList;
          });
        }
      });
    },
    getName(id) {
      let name = "";
      let item = this.biaoOptionsDict[this.form.databaseType].filter(
        (e) => id == e.dataTypeId
      );
      if (item.length) {
        name = item[0].dataTypeName;
      }
      return name;
    },
    clearForm() {
      this.form = {
        databaseType: "",
        dataTypeId: "",
        dataType: "",
        dataTableCode: "",
        dataTableName: "",
        dataColumnVoList: [
          {
            columnRequired: [],
            columnDisplay: [],
            columnOptions: [],
          },
        ],
      };
    },
    goLinkFn() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let form = JSON.parse(JSON.stringify(this.form));
          console.log("form===", form);
          let nameResult = this.getName(form.dataTypeId);
          if (nameResult) {
            form.dataTypeName = nameResult;
          } else {
            form.dataTypeName = form.dataTypeId;
            form.dataTypeId = "";
          }

          form.dataColumnVoList = form.dataColumnVoList.map((e, index) => {
            e.columnIndex = index;
            e.columnOptions = [];
            e.columnName = e.fieldAttribute;
            e.columnCode = e.fieldDescription;
            e.columnType = e.fieldType;
            e.columnDisplay = e.value7.length;
            e.columnRequired = e.value6.length;
            e.elementId = e.id;
            e.fieldLength = e.fieldLength;
            // e.metadataDictyColId = e.metadataDictyColId;
            return e;
          });
          setTimeout(() => {
            this.clearForm();
          }, 1000);
          this.$emit("confirm", form);
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    up(index) {
      if (index > 0) {
        const temp = this.form.dataColumnVoList[index];
        this.$set(
          this.form.dataColumnVoList,
          index,
          this.form.dataColumnVoList[index - 1]
        );
        this.$set(this.form.dataColumnVoList, index - 1, temp);
      }
    },
    dowm(index) {
      if (index < this.form.dataColumnVoList.length - 1) {
        const temp = this.form.dataColumnVoList[index];
        this.$set(
          this.form.dataColumnVoList,
          index,
          this.form.dataColumnVoList[index + 1]
        );
        this.$set(this.form.dataColumnVoList, index + 1, temp);
      }
    },
    deleteBtn(idx, item) {
      if (item.isExistent) {
        this.$set(
          this.form,
          "dataColumnVoList",
          this.form.dataColumnVoList.filter((item, index) => {
            if (index === idx) {
              item.isDel = 1;
            }
            return index !== -1;
          })
        );
        return;
      }
      if (this.form.dataColumnVoList.length) {
        this.$set(
          this.form,
          "dataColumnVoList",
          this.form.dataColumnVoList.filter((item, index) => {
            return index !== idx;
          })
        );
      } else {
        this.$message({
          message: "数据不能为空",
          type: "warning",
        });
      }
    },
    addBtn22() {
      this.$set(
        this.form,
        "dataColumnVoList",
        this.form.dataColumnVoList.concat({
          fieldAttribute: "",
          fieldDescription: "",
          fieldType: "",
          fieldLength: "",
          value6: false,
          value7: true,
          columnOptions3: [],
          metadataDictyColId: null,
        })
      );
    },
  },
};
</script>

<style scoped lang="scss">
.db_dialog {
  .el-dialog__body {
    padding: 0;
  }
  .step_box {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 50px;
    .step_item {
      font-family: Source Han Sans CN, Source Han Sans CN;
      font-weight: 500;
      font-size: 18px;
      color: #fff;
      position: relative;
      padding-left: 40px;

      &::before {
        content: "";
        width: 30px;
        height: 30px;
        box-sizing: border-box;
        border-radius: 15px;
        border: 3px solid #00fff4;
        position: absolute;
        top: calc(50% - 15px);
        left: 0;
      }
    }
    .steped {
      &::after {
        content: "";
        width: 16px;
        height: 16px;
        box-sizing: border-box;
        background-color: #00fff4;
        border-radius: 8px;
        position: absolute;
        top: calc(50% - 8px);
        left: 7px;
      }
    }
    .line {
      width: 270px;
      height: 2px;
      background-color: #00fff4;
      margin: 0 6px;
    }
  }
  .edit_list {
    width: 400px;
    margin: 0 auto;
    margin-top: 30px;
  }
  .columnBox {
    margin-top: 30px;
    ::v-deep .columnIte {
      width: 100%;
      font-family: Source Han Sans CN, Source Han Sans CN;
      font-weight: 500;
      font-size: 18px;
      line-height: 22px;
      color: #ffffff;
      .flexrowbottom {
        display: flex;
        align-items: flex-end;
        justify-content: space-between;
      }
      .el-form-item {
        margin-bottom: 10px;
        .el-checkbox {
          .el-checkbox__label {
            display: none;
          }
        }
      }
      .el-form-item__label {
        float: none;
      }
      .el-form-item__content {
        margin-left: 0 !important;
      }
    }
    .addbtn {
      width: 100%;
      text-align: center;
      margin-top: 50px;
    }
  }
  .edit_btns {
    margin-top: 50px;
    display: flex;
    align-self: center;
    justify-content: center;
  }
  ::v-deep .el-form--label-left .el-form-item__label {
    color: #fff;
  }
}
</style>
